<?php

function getIpInfo($ip = '') {
    if (empty($ip)) {
        $ip = get_client_ip();
    }

    $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
    if (empty($res)) {
        return false;
    }
    $jsonMatches = array();
    preg_match('#\{.+?\}#', $res, $jsonMatches);
    if (!isset($jsonMatches[0])) {
        return false;
    }
    $json = json_decode($jsonMatches[0], true);
    if (isset($json['ret']) && $json['ret'] == 1) {
        $json['ip'] = $ip;
        unset($json['ret']);
    } else {
        return "火星人";
    }
    return $json;
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装） 
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false) {
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL)
        return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos)
                unset($arr[$pos]);
            $ip = trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

function getIP() {
    if (getenv('HTTP_CLIENT_IP')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('HTTP_X_FORWARDED')) {
        $ip = getenv('HTTP_X_FORWARDED');
    } elseif (getenv('HTTP_FORWARDED_FOR')) {
        $ip = getenv('HTTP_FORWARDED_FOR');
    } elseif (getenv('HTTP_FORWARDED')) {
        $ip = getenv('HTTP_FORWARDED');
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

/**
 * 将一个object对象转化橙数组
 * @param $array
 * @return mixed
 */
function jsonDecode($array) {
    return json_decode(json_encode($array), true);
}

/**
 * 抛出异常处理
 * @param string $msg 异常消息
 * @param integer $code 异常代码 默认为0
 * @throws Think\Exception
 * @return void
 */
function E($msg, $code = 0) {
    throw new \Exception($msg, $code);
}

/* --------------------追加核心函数-------------------- */

// 实例化平台层服务,$location为类似于User/RegisterService
function service($location, $params = array()) {
    include_once PLATFROM_SERVICE_PATH . 'Service.php';
    return Platform\Services\ServiceRegist::getInstance($location, $params);
}

// 实例化平台层model
function model($location, $params = array()) {
    include_once PLATFROM_MODEL_PATH . 'Model.php';
    return Platform\Models\ModelRegist::getInstance($location, $params);
}

//调用第三方lib
function lib($location, $params = array()) {
    include_once PLATFROM_LIB_PATH . 'Lib.php';
    return Platform\Libs\LibRegist::getInstance($location, $params);
}

/** Json数据格式化
 * @param  Mixed  $data   数据
 * @param  String $indent 缩进字符，默认4个空格
 * @return JSON
 */
function jsonFormat($data, $indent = null) {
    // json encode
    $data = json_encode($data);

    // 将urlencode的内容进行urldecode
    $data = rawurldecode($data);

    // 缩进处理
    $ret = '';
    $pos = 0;
    $length = strlen($data);
    $indent = isset($indent) ? $indent : '    ';
    $newline = "\n";
    $prevchar = '';
    $outofquotes = true;

    for ($i = 0; $i <= $length; $i++) {

        $char = substr($data, $i, 1);

        if ($char == '"' && $prevchar != '\\') {
            $outofquotes = !$outofquotes;
        } elseif (($char == '}' || $char == ']') && $outofquotes) {
            $ret .= $newline;
            $pos --;
            for ($j = 0; $j < $pos; $j++) {
                $ret .= $indent;
            }
        }

        $ret .= $char;

        if (($char == ',' || $char == '{' || $char == '[') && $outofquotes) {
            $ret .= $newline;
            if ($char == '{' || $char == '[') {
                $pos ++;
            }

            for ($j = 0; $j < $pos; $j++) {
                $ret .= $indent;
            }
        }

        $prevchar = $char;
    }

    return $ret;
}

/**
 *
 * 把数组按指定的个数分隔
 * @param array $array 要分割的数组
 * @param int $groupNum 分的组数
 */
function splitArray($array, $groupNum) {
    $result = [];
    for ($i = 0; $i < ceil(count($array) / $groupNum); $i++) {
        $result[] = array_slice($array, $i * $groupNum, $groupNum);
    }

    return $result;
}

//获取RedisKey
function getRedisKey($keyPrefix, $key, $objectId = '') {
    return $keyPrefix . ':' . $key . $objectId;
}

function key_compare_func($key1, $key2) {
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

/**
 *  截取标题
 *  $string  欲截取的字符串
 *  $sublen  截取的长度
 *  $start   从第几个字节截取，默认为0
 *  $code    字符编码，默认UTF-8
 */
function cut_str($string, $sublen, $start = 0, $code = 'UTF-8') {
    if ($code == 'UTF-8') {
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);
        if (count($t_string[0]) - $start > $sublen)
            return join('', array_slice($t_string[0], $start, $sublen)) . "...";
        return join('', array_slice($t_string[0], $start, $sublen));
    } else {
        $start = $start * 2;
        $sublen = $sublen * 2;
        $strlen = strlen($string);
        $tmpstr = '';
        for ($i = 0; $i < $strlen; $i++) {
            if ($i >= $start && $i < ($start + $sublen)) {
                if (ord(substr($string, $i, 1)) > 129) {
                    $tmpstr .= substr($string, $i, 2);
                } else {
                    $tmpstr .= substr($string, $i, 1);
                }
            }
            if (ord(substr($string, $i, 1)) > 129)
                $i++;
        }
        if (strlen($tmpstr) < $strlen)
            $tmpstr .= "";
        return $tmpstr;
    }
}

/**
 * 拼接静态文件url
 * @param $url
 * @param $string
 */
function splicedUrl($url, $data) {
    return [
        'url' => $url . '/' . date('Y-m', $data['createTime']) . "/" . md5(date('Ymd', $data['createTime']) . '-' . $data['id']) . '.html',
        'share' => $url . '/' . date('Y-m', $data ['createTime']) . "/" . md5(date('Ymd', $data['createTime']) . '-share-' . $data['id']) . '.html',
    ];
}

/**
 * 获取上周1和周7的日期时间戳
 */
function getLastWeekDate($time) {
    $date = date('Y-m-d');  //当前日期
    $first = 1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
    $w = date('w', strtotime($date));  //获取当前周的第几天 周日是 0 周一到周六是 1 - 6

    $now_start = date('Y-m-d', strtotime("$date -" . ($w ? $w - $first : 6) . ' days')); //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
    $now_end = date('Y-m-d', strtotime("$now_start +6 days"));  //本周结束日期
    $last_start = date('Y-m-d', strtotime("$now_start - 7 days"));  //上周开始日期
    $last_end = date('Y-m-d', strtotime("$now_start - 1 days"));  //上周结束日期
    return [
        'thisMonday' => strtotime($now_start),
        'thisSunday' => strtotime($now_end) + 86399,
        'thisStartDay' => strtotime($date),
        'thisEndDay' => strtotime($date) + 86399,
        'lastMonday' => strtotime($last_start),
        'lastSunday' => strtotime($last_end) + 86399,
    ];
}

//二维数组排序
function arraySort($arrUsers, $sort, $limit = 6) {
    foreach ($arrUsers AS $uniqid => $row) {
        foreach ($row AS $key => $value) {
            $arrSort[$key][$uniqid] = $value;
        }
    }

    if ($sort['direction'] && !$sort['direction1']) {
        array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arrUsers);
    }
    if ($sort['direction'] && $sort['direction1']) {
        array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arrSort[$sort['field1']], constant($sort['direction1']), $arrUsers);
    }
    return array_slice($arrUsers, 0, $limit);
}

//获取3种视频清晰度的url
function getThreeVideoUrl($videoUrl) {
    $publicData = explode('/', $videoUrl);
    unset($publicData[0]);
    unset($publicData[1]);
    unset($publicData[2]);
    $mp4Info = explode('.', $publicData[6]);
    return [
        'HD' => OSS_M3U8_DOMAIN . 'Act-ss-m3u8-hd/' . $publicData[3] . '/' . $publicData[4] . '/' . $publicData[5] . '/' . $mp4Info[0] . '.m3u8',
        'LD' => OSS_M3U8_DOMAIN . 'Act-ss-m3u8-ld/' . $publicData[3] . '/' . $publicData[4] . '/' . $publicData[5] . '/' . $mp4Info[0] . '.m3u8',
        'SD' => OSS_M3U8_DOMAIN . 'Act-ss-m3u8-sd/' . $publicData[3] . '/' . $publicData[4] . '/' . $publicData[5] . '/' . $mp4Info[0] . '.m3u8',
    ];
}

function mult_unique($array) {
    $return = array();
    foreach ($array as $key => $v) {
        if (!in_array($v, $return)) {
            $return[$key] = $v;
        }
    }
    return $return;
}

//把重复的文章剔除掉
function array_unique_fb($array2D) {
    $idList = [];
    foreach ($array2D as $key => $value) {
        if (in_array($value['id'], $idList)) {
            unset($array2D[$key]);
        } else {
            $idList[] = $value['id'];
        }
    }
    return array_values($array2D);
//    foreach ($array2D as $v){
//        $v=implode(',',$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
//        $temp[]=$v;
//    }
//    $temp=array_unique($temp); //去掉重复的字符串,也就是重复的一维数组
//    foreach ($temp as $k => $v){
//        $array=explode(',',$v); //再将拆开的数组重新组装
//        //下面的索引根据自己的情况进行修改即可
//        $temp2[$k]['id'] =$array[0];
//        $temp2[$k]['categoryId'] =$array[1];
//        $temp2[$k]['title'] =$array[2];
//        $temp2[$k]['authorId'] =$array[3];
//        $temp2[$k]['author'] =$array[4];
//        $temp2[$k]['authorImg'] =$array[5];
//        $temp2[$k]['abstract'] =$array[6];
//        $temp2[$k]['thumb'] =$array[7];
//        $temp2[$k]['duration'] =$array[8];
//        $temp2[$k]['ticketCount'] =$array[9];
//        $temp2[$k]['viewCount'] =$array[10];
//        $temp2[$k]['createTime'] =$array[11];
//    }
//    return $temp2;
}

//将三维数组转成二维
function conversionArray2($result) {
    //循环遍历三维数组$arr3
    foreach ($result as $value) {
        foreach ($value as $key => $val) {
            $arr2[] = $val;
        }
    }
    return !empty($arr2) ? $arr2 : [];
}

//生成UUID
function uuid() {
    if (function_exists('com_create_guid')) {
        $uuid = com_create_guid();
    } else {
        mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45); // "-"
        $uuid = chr(123)// "{"
                . substr($charid, 0, 8) . $hyphen
                . substr($charid, 8, 4) . $hyphen
                . substr($charid, 12, 4) . $hyphen
                . substr($charid, 16, 4) . $hyphen
                . substr($charid, 20, 13)
                . chr(125); // "}"
    }
    $uuid = trim($uuid, '{}');
    return $uuid;
}

/**
 * 服务器通过get请求获得内容
 * @param  string $baseURL 基础URL
 * @param  array $keysArr 请求参数
 * @return string          [description]
 */
function http_gets($baseURL, $keysArr) {
    $url = combineURL($baseURL, $keysArr);

    $ch = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $sContent = curl_exec($ch);
    $aStatus = curl_getinfo($ch);
    curl_close($ch);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

/**
 * combineURL
 * 拼接url
 * @param string $baseURL   基于的url
 * @param array  $keysArr   参数列表数组
 * @return string           返回拼接的url
 */
function combineURL($baseURL, $keysArr) {
    if (empty($keysArr) || !is_array($keysArr))
        return $baseURL;

    $combined = $baseURL . "?";
    $valueArr = array();
    foreach ($keysArr as $key => $val) {
        $valueArr[] = "$key=" . urlencode($val);
    }
    $keyStr = implode("&", $valueArr);
    $combined .= ($keyStr);
    return $combined;
}

/**
 * 查找文本里的图片链接
 * @param $content
 * @return bool
 */
function getHtmlContentImgArray($content) {
    preg_match_all("/<img.*?src=(\"|')(.*?)(\\1).*?\>/", $content, $matchList);
    if ($matchList) {
        return $matchList[2];
    }
    return FALSE;
}

/**
 * 查找文本里的图片链接里图片全部信息
 * @param $content
 * @return bool
 */
function getImg($content) {
    preg_match_all("/<img.*\>/isU", $content, $ereg);
    if ($ereg[0]) {
        return $ereg[0];
    }
    return FALSE;
}

/**
 * 获取图片的所有参数，然后替换
 * @param string $content
 * @param $imgUrl
 * @return mixed|string
 */
function getImgThumbuUrl($content = "", $imgUrl) {

    $imgpreg = "/<img (.+?) data-src=\"(.+?)\" (.+?)>/";
    preg_match($imgpreg, $content, $info);
    if ($info) {
        $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
        $content = preg_replace($pregRule, '<img class="preload" ' . $info[1] . ' src="' . $imgUrl . '" data-src="' . $imgUrl . '" ' . $info[3] . '>', $content);
    }
    $imgpreg = "/<img (.+?) data-src=\"(.+?)\" >/";
    preg_match($imgpreg, $content, $info);
    if ($info) {
        $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
        $content = preg_replace($pregRule, '<img class="preload" ' . $info[1] . ' src="' . $imgUrl . '" data-src="' . $imgUrl . '" >', $content);
    }
    $imgpreg = "/<img data-src=\"(.+?)\" (.+?)>/";
    preg_match($imgpreg, $content, $info);
    if ($info) {
        $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
        $content = preg_replace($pregRule, '<img class="preload"  src="' . $imgUrl . '" data-src="' . $imgUrl . '" ' . $info[2] . '>', $content);
    }
    return $content;
}

//判断字符串是否经过编码方法
function is_base64($str) {
    if ($str == base64_encode(base64_decode($str))) {
        return true;
    } else {
        return false;
    }
}

//返回视频专用的时间格式
function dataformat($num) {
    $hour = floor($num / 3600);
    $hour = intval($hour) < 10 ? '0' . $hour : $hour;
    $minute = floor(($num - 3600 * $hour) / 60);
    $minute = intval($minute) < 10 ? '0' . $minute : $minute;
    $second = floor((($num - 3600 * $hour) - 60 * $minute) % 60);
    $second = intval($second) < 10 ? '0' . $second : $second;
    return $hour . ':' . $minute . ':' . $second;
}

//取一个时间的，各个时间段具体数字
function randomDivInt($div, $total) {
    $avg = $total / $div;
    $one = rand(1, $avg);
    $result[0] = $one;
    for ($i = 1; $i < $div; $i++) {
        if ($i == ($div - 1)) {
            $result[$i] = $one + $i * $avg + rand(1, $avg - $one);
        } else {
            $result[$i] = $one + $i * $avg + rand(1, $avg);
        }
    }
    return $result;


    /* $remain=$total;
      $max_sum=($div-1)*$div/2;
      $p=$div; $min=0;
      $a=array();
      for($i=0; $i<$div-1; $i++){
      $max=($remain-$max_sum)/($div-$i);
      $e=rand($min,$max);
      $min=$e+1; $max_sum-=--$p;
      $remain-=$e;
      $a[$e]=true;
      }
      $a=array_keys($a);
      $a[]=$remain;
      return $a; */
}

//删除空格
function trimall($str) {
    $qian = array(" ", "　", "\t", "\n", "\r");
    $hou = array("", "", "", "", "");
    return str_replace($qian, $hou, $str);
}

/**
 * 生成唯一邀请码
 * @return string
 */
function make_coupon_card() {
    usleep(10000);
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0, 25)]
            . strtoupper(dechex(date('m')))
            . date('d') . substr(time(), -5)
            . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));
    for (
    $a = md5($rand, true),
    $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    $d = '',
    $f = 0; $f < 6; $g = ord($a[$f]),
            $d .= $s[( $g ^ ord($a[$f + 6]) ) - $g & 0x1F],
            $f++
    )
        ;
    return $d;
}

function getTree($arr) {
    foreach ($arr as $vo) {
        if ($vo['pid'] == 0) {
            $tree[] = getchildNode($arr, $vo, $vo['id']);
        }
    }
    return $tree;
}

function getchildNode($srcArr, $parentNode, $pid) {
    foreach ($srcArr as $vo) {
        if ($vo['pid'] == $pid) {
            $node = getchildNode($srcArr, $vo, $vo['id']);
            $parentNode['children'][] = $node;
        }
    }
    return $parentNode;
}

?>
